package com.ftg.learn.framework.mybatis.mybatisinterface.service;

import com.ftg.learn.framework.mybatis.mybatisinterface.entity.StudentEntity;
import com.ftg.learn.framework.mybatis.mybatisinterface.mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;

/**
 * 业务处理
 *
 * @author lijiaxin
 * @version 1.0
 * @date 2023/9/1 14:30
 */

public class StudentServise {

    private final String resource = "mybatis.xml";

    /**
     * 封装一个方法 用来返回 sqlsession
     *
     * @return sqlsession
     */
    public SqlSession getSqlSession() {
        InputStream inputStream = null;
        try {
            //把mybatisconfiguration里面的信息读取到java里面
            inputStream = Resources.getResourceAsStream(resource);

            //建造者模式  [把xml里面的文本信息读取java并为大量的java类完成初始化赋値]
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            SqlSessionFactory sqlSessionFactory = builder.build(inputStream);
            //把你想要处理的mapper存储到factory
            sqlSessionFactory.getConfiguration().addMapper(StudentMapper.class);

            SqlSession ss = sqlSessionFactory.openSession(true);
            return ss;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public StudentEntity findOne(String stu_name){
        return getSqlSession().getMapper(StudentMapper.class).findOneName(stu_name);
    }

    public List<StudentEntity> showAll1() {
        return getSqlSession().getMapper(StudentMapper.class).showAllWithEntity();
    }

    /**
     * 修改方法
     * @param se       实体
     * @param oldId    原始id
     * @return
     */
//    public int updateStu(StudentEntity se,int oldId) {
//        return getSqlSession().getMapper(StudentMapper.class).updateStudent(se,oldId);
//    }

    public int updateStu(StudentEntity se,int oldId) {

        StudentMapper studentMapper=getSqlSession().getMapper(StudentMapper.class);
        StudentEntity ones=studentMapper.findOneId(String.valueOf(oldId));
        int sum=0;
        if(Objects.nonNull(ones)){
            sum=studentMapper.updateStudent(se,oldId);
        }
        return sum;
    }






    public int insertStu(StudentEntity se1){
        return getSqlSession().getMapper(StudentMapper.class).insertStudent(se1);
    }

    public int deleteStu(int id){
        return getSqlSession().getMapper(StudentMapper.class).deleteStudent(id);
    }

}
